package com.smart.community.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smart.community.admin.common.ex.UserException;
import com.smart.community.admin.common.utils.ShiroUtils;
import com.smart.community.admin.entity.SysUser;
import com.smart.community.admin.mapper.SysUserMapper;
import com.smart.community.admin.service.SmsService;
import com.smart.community.admin.service.SysUserService;
import com.smart.community.common.base.ex.ServiceException;
import com.smart.community.common.base.result.ResultStatus;
import com.smart.community.common.redis.dao.RedisDao;
import org.apache.shiro.authc.*;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * @author zhangwei
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Resource
    private RedisDao redisDao;
    private SysUserMapper sysUserMapper;

    @Override
    public String login(String username, String password) {
        try {
            ShiroUtils.getSubject().login(new UsernamePasswordToken(username, password));
        } catch (UnknownAccountException | IncorrectCredentialsException uae) {
            throw new UserException(ResultStatus.USER_NO_EXIST);
        } catch (LockedAccountException lae) {
            throw new UserException(ResultStatus.USER_BEEN_DELETE);
        } catch (AuthenticationException ae) {
            throw new UserException(ResultStatus.USER_AUTH_ERROR);
        }
        return ShiroUtils.getSubject().getSession(false).getId().toString();
    }

    @Override
    public String loginPhone(String phone, String code) {
        String key = String.format("%s%s", SmsService.REDIS_SMS_CODE_KEY_PREFIX, phone);
        Object redisCode = redisDao.get(key);
        if (ObjectUtils.isEmpty(redisCode)) {
            throw new ServiceException(ResultStatus.SMS_VERIFY_CODE_ERROR);
        }
        if (!code.equals(redisCode.toString())) {
            throw new ServiceException(ResultStatus.SMS_VERIFY_CODE_ERROR);
        }
        QueryWrapper<SysUser> qw = new QueryWrapper<>();
        qw.lambda().eq(SysUser::getPhone, phone);
        SysUser sysUser = sysUserMapper.selectOne(qw);
        return "登录成功";
    }
}
